package www.truongnha.com;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import TruongNhaLib.HomeClassAdapter;
import TruongNhaLib.JSONParser;
import TruongNhaLib.Model;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class HomeClass  extends ListActivity {
//    private static String getStudentListURL = "http://10.0.2.2:8080/api/getStudentList/";
//    private static String postStudentListURL = "http://10.0.2.2:8080/api/attendance/";
    private static String getStudentListURL = "http://192.168.137.1:8080/api/getStudentList/";

    private List<Model> list = new ArrayList<Model>();
    static final int DATE_DIALOG_ID = 0;
	public void onCreate(Bundle savedInstanceState) {
		    super.onCreate(savedInstanceState);
		    setContentView(R.layout.home_class);

		    final String classId = "1"; //Defaul is 1 for student in class 10A
	        new getStudentListTask().execute(getStudentListURL, classId);

	        
			// selecting single ListView item 
			ListView lv = getListView();
			
			// Launching new screen on Selecting Single ListItem
			lv.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// getting values from selected ListItem				
					String name = ((TextView) view.findViewById(R.id.std_name)).getText().toString();
					String status = ((TextView) view.findViewById(R.id.std_status)).getText().toString();
					AlertDialog alertDialog = new AlertDialog.Builder(HomeClass.this).create();
					alertDialog.setTitle(name);
					alertDialog.setMessage(status);
					alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
					      public void onClick(DialogInterface dialog, int which) {
					    	  dialog.cancel();
					    } });
					alertDialog.show();

				}
			});
			
		 }//end onCreate
	            
//AsyncTask for getStudentList:	    
     class getStudentListTask extends AsyncTask<String, Void, List<Model>>{
     	JSONObject json;
  	   	ProgressDialog dialog;
  	   	@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				Log.d("Task", "onPreExecute");
				dialog = new ProgressDialog(HomeClass.this);
				dialog.setMessage("Loading...");
				dialog.show();
				Log.d("Task", "onPreExecute");
			}

  	   		@Override
			protected List<Model> doInBackground(String... params) {
				// TODO Auto-generated method stub
  	   			Log.d("Task", "doInBackground");
	  	   		JSONObject json = JSONParser.getStudentList(params[0]);
		        try {
			        JSONArray students = json.getJSONArray("list");
			        int SIZE = students.length();
			        int index;
			        for(int i = 0; i < SIZE; i++){
			        	index = i + 1;
			            JSONObject student = students.getJSONObject(i);
			        	list.add(new Model(student.getString("id"),index,student.getString("name"),student.getString("birth"),student.getString("sex"),3 ));
			        	//Phai add them status load tu server ve(K M P ). mac dinh la 3
			        	//.............
			        }//End for.
		        } catch (JSONException e) {	
		            e.printStackTrace();
		        }//End try 
		        Log.d("Task", "Done doInBackground..");
				return list;
			}

			@Override
			protected void onPostExecute(List<Model> result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				runOnUiThread(new Runnable() {
					public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
						Log.d("Task", "onPostExecute 1");
						ArrayAdapter<Model> adapter = new HomeClassAdapter(HomeClass.this,list);
						setListAdapter(adapter);
						Log.d("Task", "onPostExecute 2");
    				
					}
				});
				dialog.dismiss();
			}
    	
     }//End class getStudentListTask
     @Override
		public void onBackPressed() {
		    AlertDialog.Builder builder = new AlertDialog.Builder(this);
		    builder.setMessage("Are you sure you want to exit?")
		           .setCancelable(false).setIcon(R.drawable.alert_icon).setTitle("Alert :))")
		           .setPositiveButton("Có", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                    HomeClass.this.finish();
		               }
		           })
		           .setNegativeButton("Không", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                    dialog.cancel();
		               }
		           });
		    AlertDialog alert = builder.create();
		    alert.show();
		}//End onBackPressed
}//End Students.java
